package com.skyable.auth.controller;

import com.skyable.auth.feign.ThirdFeignApi;
import com.skyable.auth.entity.SysUser;
import com.skyable.auth.service.IUserService;
import com.skyable.auth.utils.RedisUtil;
import com.skyable.common.constants.exception.AccountExcpConstants;
import com.skyable.common.common.ResponseResult;
import com.skyable.common.common.ServiceResult;
import com.skyable.common.constants.exception.AuthExcpConstants;
import com.skyable.common.constants.redis.RedisKeyConstants;
import com.skyable.common.utils.ParamUtil;
import com.skyable.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author GaoYuan
 * @title: UserController
 * @projectName spring-cloud-demo
 * @description: TODO
 * @date 2021/4/911:02
 */
@Api(value = "授权模块")
@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private ThirdFeignApi thirdFeignApi;


    /**
     * 生成验证码
     * @param params
     * @return
     */
    @ApiOperation(value = "生成验证码")
    @PostMapping("/user/code")
    @ApiImplicitParam(paramType="query", name = "params.phone", value = "手机号", required = true, dataTypeClass = String.class)
    public ResponseResult code(@RequestBody Map<String,String> params){
        ParamUtil.checkParams(params,"phone");

        String phone = params.get("phone");
        //判断验证码是否过期
        if(RedisUtil.hasKey(RedisKeyConstants.USER_VERITY_CODE_KEY + phone)) {
            return ResponseResult.error(AuthExcpConstants.ERROR_CODE_VERY_EXISTS,AuthExcpConstants.ERROR_MSG_VERY_EXISTS);
        }
        //查询用户是否存在
        ServiceResult<SysUser> serviceResult = userService.getUserByPhoneNum(phone);
        if(!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(),serviceResult.getMessage());
        }
        SysUser sysUser = serviceResult.getResult();
        if(sysUser == null) {
            return ResponseResult.error(AccountExcpConstants.ERROR_CODE_USER_NOT_EXISTS,AccountExcpConstants.ERROR_MSG_USER_NOT_EXISTS);
        }
        //生成并发送验证码
        String verityCode = StringUtil.generateVerityCode(6);
        params.put("code",verityCode);
        ResponseResult responseResult = thirdFeignApi.sendCode(params);
        if(!responseResult.isSuccess()) {
            return ResponseResult.error(responseResult.getCode(),responseResult.getMessage());
        }
        RedisUtil.setEx(RedisKeyConstants.USER_VERITY_CODE_KEY + phone, verityCode, 1, TimeUnit.MINUTES);
        return ResponseResult.success();
    }

}
